package NetEase;

import java.util.*;

/**
 * @author zhangmin
 * @create 2022-03-27 10:44
 * 单源点最短路径中的最大值
 */
public class 网易_2021_4 {
    class State{
        //图中节点的id
        int id;
        //从start到当前节点的最短距离
        int dis;
        public State(int id,int d){
            this.id=id;
            this.dis=d;
        }
    }

    int[] dijkstra(int start, List<int[]>[] graph){
        //distTo[i]表示从start到i的最短路
        int[] disTo=new int[graph.length];
        Arrays.fill(disTo,Integer.MAX_VALUE);
        disTo[start]=0;
        //队列按照从start出发到达路径从小到大排列
        Queue<State> pq=new PriorityQueue<>((a,b)->{
            return a.dis-b.dis;
        });
        //先将start放进去
        pq.offer(new State(start,0));
        while (!pq.isEmpty()){
            State cur = pq.poll();
            int id= cur.id,dis=cur.dis;
            if (dis<disTo[cur.id]){
                //有更短的路径到达id，不需要更新
                continue;
            }
            //将cur的相邻节点放入队列
            for (int[] neighbor:graph[id]) {
                int nextid = neighbor[0];
                int distToNext=disTo[id]+neighbor[1];
                if (disTo[nextid]>distToNext){
                    //进行松弛
                    disTo[nextid]=distToNext;
                    pq.offer(new State(nextid,distToNext));
                }
            }
        }
        return disTo;
    }


    public static void main(String[] args) {
        Scanner cin=new Scanner(System.in);
        int N= cin.nextInt(),K=cin.nextInt(),M=cin.nextInt();
        List<int[]>[] grep=new LinkedList[N+1];
        for (int i = 0; i < N + 1; i++) {
            grep[i]=new LinkedList<>();
        }
        for (int i = 0; i < M; i++) {
            int from=cin.nextInt();
            int to=cin.nextInt();
            int weight=cin.nextInt();
            grep[from].add(new int[]{to,weight});
        }
        网易_2021_4 obj=new 网易_2021_4();
        int[] disTo=obj.dijkstra(K,grep);
        int res=0;
        for (int i = 1; i < disTo.length; i++) {
            if (disTo[i]==Integer.MAX_VALUE)
            {
                System.out.println(-1);
                return;
            }
            res=Math.max(res,disTo[i]);
        }
        System.out.println(res);
    }
}
